import cv2
from aip import AipBodyAnalysis
from tkinter import *
import cv2
from PIL import Image,ImageTk

img = None
APP_ID = '16145830'
API_KEY = 'Z8QU4bk8WakFQVQUeFPSMPUB'
SECRET_KEY = 'dZkd3AngaWtuyoIYyYbTMy2zLUymiBez'
client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()
def analysis():
    try:
        list_tem=[]
        image = get_file_content('1.jpg')
        list_res = []
        for k in range(client.bodyAttr(image)['person_num']):
            list_tem = []
            dic1=client.bodyAttr(image)['person_info'][k]['attributes']
            dic_upper_wear_fg={}
            dic_upper_wear_fg['可能性']=dic1['upper_wear_fg']['score']
            dic_upper_wear_fg['属性']=dic1['upper_wear_fg']['name']
            dic_upper_wear={}
            dic_upper_wear['可能性']=dic1['upper_wear']['score']
            dic_upper_wear['属性']=dic1['upper_wear']['name']
            dic_lower_wear={}
            dic_lower_wear['可能性']=dic1['lower_wear']['score']
            dic_lower_wear['属性']=dic1['lower_wear']['name']
            dic_orientation={}
            dic_orientation['可能性']=dic1['orientation']['score']
            dic_orientation['属性']=dic1['orientation']['name']
            dic_is_human={}
            dic_is_human['可能性']=dic1['is_human']['score']
            dic_is_human['属性']=dic1['is_human']['name']
            dic_headwear={}
            dic_headwear['可能性']=dic1['headwear']['score']
            dic_headwear['属性']=dic1['headwear']['name']
            dic_gender={}
            dic_gender['可能性']=dic1['gender']['score']
            dic_gender['属性']=dic1['gender']['name']
            dic_age={}
            dic_age['可能性']=dic1['age']['score']
            dic_age['属性']=dic1['age']['name']
            dic_glasses={}
            dic_glasses['可能性']=dic1['glasses']['score']
            dic_glasses['属性']=dic1['glasses']['name']
            result={}
            result['上身服饰']=dic_upper_wear_fg
            result['上衣类型']=dic_upper_wear
            result['裤子类型']=dic_lower_wear
            result['哪一面']=dic_orientation
            result['人体是否正常']=dic_is_human
            result['帽子']=dic_headwear
            result['性别']=dic_gender
            result['年龄']=dic_age
            result['眼镜']=dic_glasses
            list_tem.append('眼镜:%s' % result['眼镜'])
            list_tem.append('上身服饰:%s'%result['上身服饰'])
            list_tem.append('上衣类型:%s'%result['上衣类型'])
            list_tem.append('裤子类型:%s'%result['裤子类型'])
            list_tem.append('帽子:%s'%result['帽子'])
            list_tem.append('性别:%s'%result['性别'])
            list_tem.append('年龄:%s'%result['年龄'])
            list_tem.append('哪一面:%s' % result['哪一面'])
            list_tem.append('人体是否正常:%s' % result['人体是否正常'])
            list_res.append(list_tem)
        return list_res
    except:
        return  None


def photos():
    global new, camera,i
    success, img = camera.read()
    # 从摄像头读取照片
    if success:
        a = cv2.waitKey(0) & 0xFF
        cv2.imwrite('1' + '.jpg', img)

        # listb = Listbox(root, height=20, width=70)
        # for item in result:  # 第一个小部件插入数据
        #     listb.insert(0, item)
        cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)
        faces = faceCascade.detectMultiScale(
            cv2image,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(30, 30)
            # flags = cv2.CV_HAAR_SCALE_IMAGE
        )
        if faces!=():
            result2=[]
            if i%40==0:
                result2 = analysis()  # 属性结果
                if result2!=None:
                    for k in range(len(result2)):
                        print(result2[k])
            # Draw a rectangle around the faces
            for (x, y, w, h) in faces:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            # Display the resulting frame
            # cv2.imshow('frame', img)

            cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)
            current_image = Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=current_image)
            panel.imgtk = imgtk
            panel.config(image=imgtk)
            # result = Label(root,text = result2,height = 500,width = 10)
            # result.place(x=2000, y=100)
            if i%40==0:
                if result2 != None:
                    listb.delete(0,END)
                    for h in range(len(result2)):
                        for item in result2[h]:  # 第一个小部件插入数据
                            listb.insert(0, item)
                listb.pack(side=RIGHT)
            # if i%39==0:
            #     listb.destroy()
            # if result2 != None:
            #     # for k in range(len(result2)):
            #     result.text="%s"% result2
            # result.pack(side=RIGHT)
            root.update()
            root.after(0, photos)
            i+=1
        else:
            current_image = Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=current_image)
            panel.imgtk = imgtk
            panel.config(image=imgtk)
            root.update()
            root.after(1, photos)

camera = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
root = Tk()
root.geometry('800x650+500+0')
panel = Label(root,text = 1,height = 400,width = 400)
panel.place(x = 10,y = 100)
listb = Listbox(root,height=20, width=55)
i=0
photos()
root.mainloop()